#include "logger.h"
#include "memory"
#include "time.h"
#include "iostream"
#include <unistd.h>

// 获取日志的单例
Logger& Logger::GetInstance()
{
    static Logger logger;
    return logger;
}

Logger::Logger() {
    std::thread writeLogTask(
        [&]()->void{
            for(;;) {
                time_t t = time(nullptr);
                tm *nt = localtime(&t); 

                char file_name[128];
                sprintf(file_name, "%d-%d-%d.txt", nt->tm_year+1900, nt->tm_mon+1, nt->tm_mday);
                FILE *fp = fopen(file_name, "a+");
                if (fp == nullptr) {
                    std::cout << "logger file : " << file_name << " open error!" << std::endl;
                    exit(EXIT_FAILURE);
                }
                std::string msg = m_lckQue.Pop();
                char time_buf[128];
                sprintf(time_buf, "%d-%d-%d [%s] ", nt->tm_hour, nt->tm_min, nt->tm_sec, (m_loglevel==INFO ? "INFO" : "ERROR"));
                msg.insert(0, time_buf);
                msg.append("\n");
                fputs(msg.c_str(), fp);
                fclose(fp);
            }
        }
    );
    writeLogTask.detach();
}

// 设置日志级别 
void Logger::SetLogLevel(LogLevel level)
{
    m_loglevel = level;
}

// 写日志， 把日志信息写入lockqueue缓冲区当中
void Logger::Log(std::string msg)
{
    m_lckQue.Push(msg);
}